from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()

# Create your models here.
# 博客分类表
class BlogCategory(models.Model):
    name = models.CharField(max_length=200, verbose_name='分类名称')

    def __str__(self):
        return self.name
    
    class Meta:
        verbose_name = '博客分类'
        verbose_name_plural = verbose_name

# 博客表
class Blog(models.Model):
    title = models.CharField(max_length=200, verbose_name='博客标题')
    content = models.TextField(verbose_name='博客内容')
    pub_time = models.DateTimeField(auto_now_add=True, verbose_name='发布时间')
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='作者')
    category = models.ForeignKey(BlogCategory, on_delete=models.CASCADE, verbose_name='分类')

    def __str__(self):
        return self.title
    
    class Meta:
        verbose_name = '博客'
        verbose_name_plural = verbose_name
        ordering = ['-pub_time']  # 按发布时间降序排列

# 评论表
class BlogComment(models.Model):
    content = models.TextField(verbose_name='评论内容')
    pub_time = models.DateTimeField(auto_now_add=True, verbose_name='评论时间')
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='评论作者')
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name="comments", verbose_name='博客')

    def __str__(self):
        return f'评论: {self.content[:20]}... by {self.author.username}'
    
    class Meta:
        verbose_name = '博客评论'
        verbose_name_plural = verbose_name
        ordering = ['-pub_time']